<template>
  <!-- 工程措施问题清单 -->
  <base-breadcrumb :title="$route.meta.title" :breadcrumb="!isModal">
  <a-row :gutter="10" class="page-height">
      <a-col :span="6">
        <a-card
          style="border-right:1px solid #d9d9d9" 
            class="page-height-tree"
          >
          <!-- 分部分项 -->
          <tree-search
            ref="treeSearch"
            :api="api"
            is-all
            :selectedKeys.sync="selectedKeys"
            :selectOptions.sync="selectOptions"
            :init-expand-all="false"
            :showRiskButton="!isModal"
            :isShowEnabled="isModal"
            emptyDescription="暂无数据"
            :riskJudgmentTreeQuery="true"
            @refreshTab="loaderTree"
            @loader="loaderTree"
            :autoSelect="false"
          />
        </a-card>
      </a-col>
      <a-col :span="18"  class="page-height-list-wrapper" style="background:#fff">
        <a-spin :spinning="spinning" tip="风险等级加载中..." style="width:100%">
          <div class="card-container" v-if="levelIdList.length > 0">
            <!-- 风险等级 -->
            <a-tabs type="card" :animated="false" v-model="levelId" @change="handleChange" size="large">
              <!-- 风险等级列表 -->
              <a-tab-pane v-for="item in levelIdList" :key="item.id" :tab="item.name">
                <div class="mb12">
                  <a-button
                    v-btnPermission="'qm_055_add_05'"
                    v-if="!isModal"
                    type="primary"
                    :disabled="selectedKeys.length < 1 || selectOptions.parentId == null || selectOptions.hasChildren"
                    @click="handleManage(0)"
                  >
                    添加判定标准
                  </a-button>
                </div>
                <div class="page-height-list">
                  <!-- 表格 -->
                  <list-table
                    :ref="'tables' + item.id"
                    table-layout="fixed"
                    size="default"
                    :row-key="(record) => record.id"
                    :outSelectedRowKeys="tableSlectedRowKeys"
                    :columns="columns"
                    :request="loadData"
                    :alert="true"
                    :isScrollX="false"
                    :selectConfig="{use: isModal, type: 'checkbox',rowKey: 'id' }"
                    @select-click="selectClick"
                    show-size-changer
                    show-quick-jumper
                    show-pagination="auto"
                  >
                    <!-- 表格行操作栏 -->
                    <span slot="action" slot-scope="text, record">
                      <MoreButton v-if="!isModal">
                        <a v-btnPermission="'qm_055_loo_07'" @click="handleManage(2, record)">查看</a>
                        <a v-btnPermission="'qm_055_edi_06'" @click="handleManage(1, record)">编辑</a>
                        <a-divider v-btnPermission="!record.enabled ? 'qm_055_sta_09' : 'qm_055_sto_08'" type="vertical" />
                        <a v-btnPermission="'qm_055_sta_09'" v-if="!record.enabled" @click="handleRemove(record)">启用</a>
                        <a v-btnPermission="'qm_055_sto_08'" v-else class="del_btn" @click="handleRemove(record)">停用</a>
                      </MoreButton>
                    </span>
                  </list-table>
              </div>
              </a-tab-pane>
            </a-tabs>
          </div>
          
          <div v-if="levelIdList.length == 0 && !spinning" class="mb12" align="center" style="width: 100%">
            <b>暂无风险等级</b>
          </div>
        </a-spin>

      </a-col>
    </a-row>
    <!-- 问题分类表单弹窗 -->
    <a-modal
    :title="headerTitle"
    :visible.sync="visible"
    @cancel="visible = false"
    width="900px"
  >
    <a-form-model
      ref="ruleForm"
      :model="form"
      :rules="editModel != 2 ? rules : {}"
      :label-col="{ span: 8 }"
      :wrapper-col="{ span: 14 }"
    >
    <a-row>
      <a-col>
        <a-form-model-item
          prop="description"
          label="判定标准描述"
        >
          <BaseTextarea
            v-model.trim="form.description"
            :disabled="editModel == '2'"
          />
        </a-form-model-item>
        <a-form-model-item
          prop="enabled"
          label="状态"
        >
          <a-switch 
            checked-children="启用" 
            un-checked-children="停用" 
            :disabled="editModel == '2'" 
            v-model="form.enabled" 
          />
        </a-form-model-item>
      </a-col>
    </a-row>
    </a-form-model>
    <!-- 页脚操作栏 -->
    <div
      slot="footer"
    >
      <a-button  @click="visible = false">
        关闭
      </a-button>
      <a-button
        v-if="editModel != 2"
        :loading="submitFormLoading"
        type="primary"
        class="button_right"
        @click="submitForm"
      >
        提交
      </a-button>
    </div>
  </a-modal>
  </base-breadcrumb>
</template>

<script>
import { riskcriteriaList, riskcriteriaCreate, riskcriteriastatus, riskcriteriaupdate, subItem } from '@/api/quality/risk/universal' // 通用api
import TreeSearch from '@/components/businessComponents/TreeSearch' // 树
import { qualityTypeLabel } from '@/api/quality/projectDivision' // api
import { mapGetters } from 'vuex'
const columns1 = [
  {
    title: '序号',
    width: '80px',
    customRender(text, record, index) {
      return index + 1
    }
  },
  {
    title: '判定标准描述',
    ellipsis: true,
    dataIndex: 'description',
    width: 180,
  },
  {
    title: '状态',
    dataIndex: 'enabled',
    width: 180,
    customRender(text, record, index) {
      return text ? '可用' : '不可用'
    }
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: 180,
    scopedSlots: { customRender: 'action' }
  }
]
const columns2 = [
  {
    title: '序号',
    width: '80px',
    customRender(text, record, index) {
      return index + 1
    }
  },
  {
    title: '判定标准描述',
    ellipsis: true,
    dataIndex: 'description',
    width: 180,
  },
  {
    title: '状态',
    dataIndex: 'enabled',
    width: 180,
    customRender(text, record, index) {
      return text ? '可用' : '不可用'
    }
  },
]
export default {
  name: 'a' + Date.now(),
  components: {
    TreeSearch,
  },
  computed: {
    ...mapGetters(['btnPermission']),
    // 弹窗动态标题
    headerTitle() {
      return ['添加判断标准', '编辑判断标准', '查看判断标准'][this.editModel]
    },
    api() {
      return subItem
    },
    // 禁用添加
    addDisable() {
      // qualityApiUrl = '/cscec-quality-business'
      return ''
    }
  },
  props: {
    // 是否弹框
    // 只读模式
    isModal: {
      type: Boolean,
      default: false
    },
    // 选中 key
    outSelectedRowKeys: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    isModal: {
      handler(val) {
        if (val) {
          this.columns = columns2
        } else {
          this.columns = columns1
        }
      },
      immediate: true,
      deep: true
    },
    outSelectedRowKeys: {
      handler(val) {
        this.tableSlectedRowKeys = val
        this.selectRow = this.selectRow.filter(item => !val.includes(item.id))
      },
      immediate: true,
      deep: true
    }
  },
  data() {
    return {
      // 操作类型：0 添加 1 编辑 3 查看
      editModel: 0,
      // 责任区域弹窗控件
      visible: false,
      submitFormLoading: false,
      selectedKeys: [], // 选中节点
      // 弹窗参数
      form: {
        id: '',
        description: '',
        enabled: true,
        treeId: '',
        levelId: '',
      },
      columns: [],
      levelId: '',
      spinning: false,
      dataLoading: false,
      levelIdList: [],
      selectRow: [],
      oldTreeId: '',
      vewTreeId: '',
      tableSlectedRowKeys: [], // 指定选中项的 key 数组
      // 选中节点对象
      selectOptions: {},
      //动态操作按钮配置
      rules: {
        description: [{ required: true, message: '请输入判定标准描述', trigger: 'change' }],
      },
    }
  },
  mounted() {
    this.$refs.treeSearch && this.$refs.treeSearch.getList()
    this.getCheckType()
  },
  methods: {
    loadData(parameter) {
      if (this.selectedKeys?.length && this.levelId && this.selectOptions?.parentId) {
        const arg = {
          query: {
            id: null,
            enabled: this.isModal ? true : null,
            treeId: this.selectOptions.id, 
            levelId: this.levelId
          }
        }
        this.dataLoading = true
        const requestParameters = Object.assign({}, parameter, arg )
        return riskcriteriaList(requestParameters).then((res) => {
          if (res.data) {
            res.data.map(item => item.disabled = !item.enabled)
          }
          this.dataLoading = false
          return res
        }).catch(() => {
          this.dataLoading = false
        })
      }
    },
    selectClick(obj) {
      const rows = obj.rows.map(item => {
        item.treeName = this.selectOptions.name
        return item
      })
      this.tableSlectedRowKeys = rows.map(item => item.id)
      this.selectRow = rows
    },
    //获取检查类别
    getCheckType(){
      this.spinning = true
      qualityTypeLabel({type:59}).then((res)=>{
        if(res.code==200){
          this.levelIdList = res.data.filter(item => item.code !== '4');
          if (this.levelIdList.length > 0) {
            this.levelId = this.levelIdList[0].id
          }
        }
        this.spinning = false
      }).catch(() => {
        this.spinning = false
      })
    },
    // 头部搜索
    loaderTree(value) {
      this.vewTreeId = this.selectOptions.id
      this.$nextTick(() => {
        if (this.$refs['tables' + this.levelId] && this.$refs['tables' + this.levelId].length) {
          this.$refs['tables' + this.levelId][0].refresh(true)
          // 改变 tableSlectedRowKeys 触发 watch
          if (!this.tableSlectedRowKeys.includes('newid')) {
            this.tableSlectedRowKeys.push('newid')
          } else {
            const index = this.tableSlectedRowKeys.indexOf('newid')
            this.tableSlectedRowKeys.splice(index, 1)
          }
        }
      })
    },
    handleChange(val) {
      if (this.dataLoading) {
        return false
      }
      if (this.$refs['tables' + this.levelId] && this.$refs['tables' + this.levelId].length > 0) {
        if (this.vewTreeId !== this.oldTreeId) {
          this.$refs['tables' + this.levelId][0].refresh(true)
          this.oldTreeId = this.selectOptions.id
        } else {
          this.$refs['tables' + this.levelId][0].refresh(true)
        }
      }
      // 改变 tableSlectedRowKeys 触发 watch
      if (!this.tableSlectedRowKeys.includes('newid')) {
        this.tableSlectedRowKeys.push('newid')
      } else {
        const index = this.tableSlectedRowKeys.indexOf('newid')
        this.tableSlectedRowKeys.splice(index, 1)
      }
    },
    // 提交问题分类表单
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let name = ['create', 'update'][this.editModel] // 根据操作切换url地址
          this.form.treeId = this.selectOptions.id
          this.form.levelId = this.levelId
          let requestApi = name === 'create' ? riskcriteriaCreate : riskcriteriaupdate
          this.submitFormLoading = true
          requestApi(this.form)
            .then((res) => {
              this.$message.success(['添加', '编辑'][this.editModel] + '成功！')
              this.visible = false
              if (this.$refs['tables' + this.levelId]) {
                this.$refs['tables' + this.levelId][0].loadData()
              }
              this.submitFormLoading = false
            })
            .catch((res) => {
              this.submitFormLoading = false
            })
        }
      })
      
    },
    // 停启用
    handleRemove(e) {
      let enabled = e.enabled ? '停用': '启用'
      this.$confirm({
        title: '温馨提示',
        content: `确认${enabled}？`,
        okText: '提交',
        cancelText: '关闭',
        onOk: () => {
          this.form.treeId = this.selectOptions.id
          this.form.levelId = this.levelId
          this.form.description = e.description
          this.form.enabled = !e.enabled
          this.form.id = e.id
          return riskcriteriastatus(this.form).then((res) => {
            this.$message.success(enabled + '成功！')
            if (this.$refs['tables' + this.levelId]) {
              this.$refs['tables' + this.levelId][0].loadData()
            }
          })
        }
      })
    },
    // 业务区域：新增/编辑/查看
    handleManage(b, a) {
      // b 操作类型;a 行数据
      if (b) {
        this.form.treeId = this.selectOptions.id
        this.form.levelId = this.levelId
        this.form.description = a.description
        this.form.enabled = a.enabled
        this.form.id = a.id
      } else {
        // if (this.selectOptions.hasChildren) {
        //   this.$message.warning('该节点下已存在判定标准，若继续添加节点，则该节点下的判定标准不能使用！')
        // }
        this.form.treeId = this.selectOptions.id
        this.form.levelId = this.levelId
        this.form.description = ''
        this.form.enabled = true
        this.form.id = ''
      }
      this.editModel = b
      // 添加
      this.visible = true // 打开弹窗
      this.$nextTick(() => {
        this.$refs.ruleForm && this.$refs.ruleForm.clearValidate();
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .card-container {
  background: #fff;
  overflow: hidden;
  padding: 24px 5px;
}
</style>

